//
//  RAPPullDownRefreshControl.swift
//  COPYCAT-Weibo
//
//  Created by 闫萌 on 1/3/16.
//  Copyright © 2016 RendezvousAuParadis. All rights reserved.
//

import UIKit

private let kControlHeight:CGFloat = 60

///  下拉刷新控件的状态枚举
///
///  - Normal:     普通状态
///  - Ready:      准备就绪
///  - Refreshing: 正在刷新
private enum RAPPullDownState {
    case Normal
    case Ready
    case Refreshing
}


/// 自定义下拉刷新控件
class RAPPullDownRefreshControl: UIControl {
    /**
    作为其super view的scroll view
    */
    private var superScrollView: UIScrollView?
    
    
    private var controlState: RAPPullDownState = .Normal {
        didSet {
            switch controlState {
            case .Normal: // 普通状态
                messageLabel.text = "下拉刷新"
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowView.transform = CGAffineTransformIdentity
                })
            case .Ready: // 就绪状态
                messageLabel.text = "放手起飞"
//                arrowView.hidden = false
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing: // 正在刷新状态
                messageLabel.text = "正在刷新"
                arrowView.hidden = true
                indicator.startAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    superScrollView?.contentInset.top = kControlHeight + 64
                })
                // 这个方法可以同UIButton类似
                sendActionsForControlEvents(UIControlEvents.ValueChanged)
                
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor(white: 237 / 255.0, alpha: 1)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    ///  这个方法在view被添加至父视图时调用
    ///
    ///  - parameter newSuperview: 父视图
    override func willMoveToSuperview(newSuperview: UIView?) {
        superScrollView = newSuperview as? UITableView
        self.frame = CGRectMake(0, -kControlHeight , newSuperview!.bounds.width, kControlHeight)
        
        superScrollView?.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
        
        setupSubViews()
    }
    
    private func setupSubViews() {
        addSubview(messageLabel)
        addSubview(arrowView)
        addSubview(indicator)
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(10)
            make.centerY.equalTo(self)
        }
        
        arrowView.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(messageLabel.snp_leading)
            make.centerY.equalTo(self)
        }
        
        indicator.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowView)
        }
    }
    
    
    private lazy var messageLabel: UILabel = {
        let messageLabel = UILabel(text: "", fontSize: 12, textColor: UIColor.lightGrayColor())
        
        return messageLabel
        }()
    
    private lazy var arrowView: UIImageView = {
        let arrowView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
        
        return arrowView
    }()
    
    private lazy var indicator: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: .White)
        
        return indicator
    }()
    
    ///  KVO的通知接收方法
    ///
    ///  - parameter keyPath: 键
    ///  - parameter object:  发送KVO通知的对象
    ///  - parameter change:  包含变化的值的字典
    ///  - parameter context: 其他信息
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let tableView = object as! UITableView
        // table view 偏移量
        let offset = (change![NSKeyValueChangeNewKey] as! NSValue).CGPointValue()
        
        if tableView.contentInset.top == 104 || offset.y > -64  {
            return
        }
        /*
        当下拉至控件全部显示时，且手指处于拖动状态，控制状态更新至ready
        */
        if abs(offset.y) > kControlHeight + tableView.contentInset.top {
            if tableView.dragging {
                controlState = .Ready
            }
            
            if tableView.decelerating {
                controlState = .Refreshing
            }
        
        }else {
            controlState = .Normal
        }
    }
    
    // MARK: - 控制刷新的方法
    func endRefreshing() {
        indicator.stopAnimating()
        arrowView.hidden = false
        superScrollView?.contentInset.top = 64
    }
}
